<?php
/**
 * 项目管理控制器
*
* PHP version 5
*
* @package   Ecga
* @author    Farmer.Li <lixu_01@126.com>
* @copyright 2010 Xingchangxinda Inc.
* @version   SVN: $Id$
*/
namespace Project\Apps\Ecga\Controllers;

use \Project\Apps\Ecga\Controllers\Abstraction\EcgaController;
use \Framework\System\Helper\HttpResponse;
use \Project\Apps\Ecga\Models\Projects as ProjectsBiz;
use \Framework\Controller\ControllerException;
use \Project\Apps\Ecga\Library\Visitor;
use \Framework\Mapper\FieldException;

/**
 * 项目管理控制器
 *
 * PHP version 5
 *
 * @package   Ecga
 * @author    Farmer.Li <lixu_01@126.com>
 * @copyright 2010 Xingchangxinda Inc.
 * @version   Release: <0.1>
 **/
class Projects extends EcgaController
{
    /**
     * 获取有权限的项目 option数组格式
     * 
     * @return array
     */
    private static function _getAllowProject()
    {
        static $projects = null;
        if (null != $projects) {
            return $projects;
        }
        $ns = get_called_class();
        $tableName = substr($ns, strrpos($ns, '\\') + 1);
        $projects = model('Projects')->getOptions();
        if ($projects) {
            $passport = Visitor::getInstance()->getPassport();
            foreach ($projects as $key => $value) {
                //去除没有查看权限的项目
                if (!$passport->hasProjectPriviage($key, $tableName)) {
                    unset($projects[$key]);
                }
            }
        }
        return $projects;
    }

	/**
	 * 显示数据表
	 *
	 * @param HttpRequest $request Http请求
	 *
	 * @return void
	 */
	public static function show($request)
	{
		$page = self::createPage();
		$page->setTitle('项目列表');
		$projectModel = model('Projects');
        $pageNo = $request->get('page', 'int', 1);
        $allowProjects = array_keys(self::_getAllowProject());
        $filter = array(
            'id' => $allowProjects
        );
		$list = self::createDataList(ProjectsBiz::getPageQuery($filter))
            ->setCurrentPage($pageNo)
            ->orderBy('id', 'desc');
		$page->assign('list', $list)
            ->assign('userId', Visitor::getInstance()->userId);
		HttpResponse::output($page->render('projectlist'));
	}
	
	/**
	 * 添加项目
	 * 
	 * @param HttpRequest $request Http请求
	 * 
	 * @return void
	 */
	public static function add($request)
	{
        if (1 == Visitor::getInstance()->userId) {
            return;
        }
        
		$page = self::createPage();
		$page->setTitle('添加项目');
		HttpResponse::output($page->render('projectdetail'));
	}
	
	/**
	 * 执行添加项目
	 *
	 * @param HttpRequest $request Http请求
	 *
	 * @return void
	 */
	public static function doAdd($request) 
	{
		$data = self::_getFormData($request);
		$project = model('Projects')->create();
		try {
			self::_save($project, $data);
		} catch (ControllerException $e) {
			HttpResponse::jsonResult(false, $e->getMessage());
			return false;
		}
		
		$msg = '已成功添加项目 ' . $data['projectName'];
		self::message($msg);
		HttpResponse::jsonResult(true, $msg);
	}
	
	/**
	 * 编辑
	 * 
	 * @param HttpRequest $request Http请求
	 *
	 * @return void
	 */
	public static function edit($request)
	{
		$page = self::createPage();
		$page->setTitle('编辑项目');
		$id = $request->get('id', 'int');
		$project = model('Projects')->get($id);
		if (!$project) {
            self::message('未找到指定项目', 'warning', 'projects.php?a=show');
            return false;
        }
        $page->assign('project', $project);
		HttpResponse::output($page->render('projectdetail'));
	}
	
	/**
	 * 执行编辑
	 * 
	 * @param HttpRequest $request Http请求
	 *
	 * @return void
	 */
	public static function doEdit($request)
	{
		$id = $request->get('id', 'int');
		$project = model('Projects')->get($id);
		if (!$project) {
			self::message('未找到指定项目', 'warning', 'projects.php?a=show');
			return false;
		}
		$data = self::_getFormData($request);
		try {
            self::_save($project, $data); 
        } catch (ControllerException $e) {
            HttpResponse::jsonResult(false, $e->getMessage());
            return false;
        }        
        $msg = '已成功修改部门 ' . $data['projectName'];
        self::message($msg);
        HttpResponse::jsonResult(true, $msg);
	}
	
	/**
	 * 获取表单数据
	 * 
	 * @param HttpRequest $request Http请求
	 * 
	 * @return array
	 */
	private static function _getFormData($request)
	{
		$data = array(
			'projectName' => $request->post('projectName', 'string'),
			'batchConfig' => $request->post('batchConfig', 'string')
		);
		//处理采集批次
		$batch = str_replace('，', ',', $data['batchConfig']);
		$batch = array_unique(explode(',', $batch));
		$batch = array_map('intval', $batch);
		foreach ($batch as $key => $value) {
			if ($value < 0 || $value > 23) {
				unset($batch[$key]);
			}
		}
		$data['batchConfig'] = implode(',', $batch);
		return $data;
	}
	/**
     * 执行保存动作
     *
     * @param entity $entity 模型实体
     * @param array  $data   项目数据
     * 
     * @return void
     */
    private static function _save($entity, $data)
    {
        try {
            $entity->setAttributes($data)->save();
        } catch (FieldException $e) {
            switch ($e->getCode()) {
            case FieldException::BLANK_VALUE :
                if ($e->field == 'projectName') {
                    $message = '对不起，项目名称不能为空。';
                } elseif ($e->field == 'batchConfig') {
                    $message = '对不起，采集批次不能为空。';
                } else {
                    throw $e;
                }
                break;
            case FieldException::UNIQUE_VALUE :
                $message = '对不起，相同名称的项目已存在。';
                break;
            case FieldException::INVALUD_VALUE :
                break;
            default:
                throw $e;
            }
            throw new ControllerException($message);
        }
    }
}
?>